package com.pactera.asmp.server.common.email;

import com.pactera.asmp.server.common.utils.EmailUtils;
import com.pactera.asmp.server.dao.ProjectMapper;
import com.pactera.asmp.server.pojo.ProjectInfo;
import io.swagger.models.auth.In;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.FileSystemResource;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.JavaMailSenderImpl;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.FileDataSource;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.internet.*;

import java.io.File;
import java.util.*;

/**
 * @ProjectName: asmpserver
 * @Package: com.pactera.asmp.server.common.email
 * @ClassName: EmailServiceImpl
 * @Author: lvzhiqiang
 * @Description: ASMP邮件发送服务实现
 * @Date: 2019/7/25 16:08
 * @Version: 1.0
 */
@Service
public class EmailServiceImpl implements IMailService {
    private final Logger logger = LoggerFactory.getLogger(EmailServiceImpl.class);

    @Value("${spring.mail.username}")
    private String from;

    @Autowired
    private JavaMailSender mailSender;

    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.image.path.example_img}")
    private String IMAGE_PATH_EXAMPLE;

    @Value("${spring.mail.image.path.email_logo}")
    private String IMAGE_PATH_EMAIL_LOGO;


    @Async
    @Override
    public void sendSimpleMail(String to, String subject, String content) {
        //JavaMailSenderImpl mailSender =  getMailSender(projectId);
        SimpleMailMessage message = new SimpleMailMessage();
        message.setTo(to);//收信人
        message.setSubject(subject);//主题
        message.setText(content);//内容
        message.setFrom(from);//发信人
        mailSender.send(message);
    }

    @Async
    @Override
    public void sendHtmlMail(String to, String subject, String content) {
        logger.info("发送HTML邮件开始：{},{},{}", to, subject, content);
        //使用MimeMessage，MIME协议
        //JavaMailSenderImpl mailSender =  getMailSender(projectId);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);//true代表支持html
            mailSender.send(message);
            logger.info("发送HTML邮件成功");
        } catch (MessagingException e) {
            logger.error("发送HTML邮件失败：", e);
        }
    }

    @Override
    public void sendAttachmentMail(String to, String subject, String content, String filePath) {
        logger.info("发送带附件邮件开始：{},{},{},{}", to, subject, content, filePath);
        //JavaMailSenderImpl mailSender =  getMailSender(projectId);
        MimeMessage message = mailSender.createMimeMessage();

        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            //true代表支持多组件，如附件，图片等
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource file = new FileSystemResource(new File(filePath));
            String fileName = file.getFilename();
            helper.addAttachment(fileName, file);//添加附件，可多次调用该方法添加多个附件
            mailSender.send(message);
            logger.info("发送带附件邮件成功");
        } catch (MessagingException e) {
            logger.error("发送带附件邮件失败", e);
        }
    }

    @Override
    public void sendInlineResourceMail(String to, String subject, String content, String rscPath, String rscId) {
        logger.info("发送带图片邮件开始：{},{},{},{},{}", to, subject, content, rscPath, rscId);
        //JavaMailSenderImpl mailSender =  getMailSender(projectId);
        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom(from);
            helper.setTo(to);
            helper.setSubject(subject);
            helper.setText(content, true);
            FileSystemResource res = new FileSystemResource(new File(rscPath));
            helper.addInline(rscId, res);//重复使用添加多个图片
            mailSender.send(message);
            logger.info("发送带图片邮件成功");
        } catch (MessagingException e) {
            logger.error("发送带图片邮件失败", e);
        }
    }

    @Async
    @Override
    public void sendBatchMailWithFile(String[] toEmails,String[] ccEmails, String subject, String text, String[] filePath) throws Exception {
        //JavaMailSenderImpl mailSender =  getMailSender(projectId);
        MimeMessage mimeMessage = mailSender.createMimeMessage();
        MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
        messageHelper.setFrom(from);
        messageHelper.setSubject(subject);
        MimeMultipart multipart = new MimeMultipart("related");
        EmailUtils.addAttchments(filePath, text, multipart, mimeMessage, messageHelper);
        InternetAddress[] toAddress = EmailUtils.getIntenetAddressList(toEmails);
        mimeMessage.setRecipients(Message.RecipientType.TO, toAddress);
        InternetAddress[] ccAddress = EmailUtils.getIntenetAddressList(ccEmails);
        mimeMessage.setRecipients(Message.RecipientType.CC, ccAddress);
        mimeMessage = messageHelper.getMimeMessage();
        mailSender.send(mimeMessage);
        logger.info("sendBatchMailWithFile: 发送成功");
    }




    @Async
    @Override
    public void sendBatchMailByTemplate(String[] toEmails, String[] ccEmails, String subject, String[] attachmentPath, String tamplateName, Map<String, Object> dataMap, File pdfFile, String projectName) throws Exception {
        try {
            JavaMailSenderImpl mailSender =  getMailSender(0,projectName);
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            messageHelper.setFrom(from);
            messageHelper.setSubject(subject);
    
            String templateInfo = EmailUtils.createTemplates(dataMap, tamplateName, templateEngine);
            MimeMultipart multipart = new MimeMultipart("related");
    
            EmailUtils.addAttchments(attachmentPath, templateInfo, multipart, mimeMessage, messageHelper);
    //        EmailUtils.addImageResource(IMAGE_PATH_EXAMPLE, "analyse_image", multipart);
    //        EmailUtils.addImageResource(IMAGE_PATH_EMAIL_LOGO, "logo_image", multipart);
            if(null != pdfFile) {
                DataSource dataSource = new FileDataSource(pdfFile);
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setDataHandler(new DataHandler(dataSource));
                mimeBodyPart.setFileName(MimeUtility.encodeText(String.format("%s.pdf", subject)));
                multipart.addBodyPart(mimeBodyPart);
            }
    
            EmailUtils.setRecipients(toEmails, mimeMessage,Message.RecipientType.TO);
            EmailUtils.setRecipients(ccEmails, mimeMessage,Message.RecipientType.CC);
            mimeMessage = messageHelper.getMimeMessage();
            mailSender.send(mimeMessage);
            logger.info("sendBatchMailByTemplate: 发送成功");
        }finally {
            if(null != pdfFile) {
                pdfFile.delete();
            }
        }
    }

    @Async
    @Override
    public void sendBatchMailByTemplate(String[] toEmails, String[] ccEmails, String subject, String[] attachmentPath, String tamplateName, Map<String, Object> dataMap, File pdfFile, List<File> excelFiles, Integer projectId) throws Exception {
        try {
            JavaMailSenderImpl mailSender =  getMailSender(projectId, "");
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            MimeMessageHelper messageHelper = new MimeMessageHelper(mimeMessage, true, "UTF-8");
            //messageHelper.setFrom(from);
            messageHelper.setFrom(mailSender.getUsername());
            messageHelper.setSubject(subject);

            String templateInfo = EmailUtils.createTemplates(dataMap, tamplateName, templateEngine);
            MimeMultipart multipart = new MimeMultipart("related");

            EmailUtils.addAttchments(attachmentPath, templateInfo, multipart, mimeMessage, messageHelper);
            //        EmailUtils.addImageResource(IMAGE_PATH_EXAMPLE, "analyse_image", multipart);
            //        EmailUtils.addImageResource(IMAGE_PATH_EMAIL_LOGO, "logo_image", multipart);
            if(null != pdfFile) {
                DataSource dataSource = new FileDataSource(pdfFile);
                MimeBodyPart mimeBodyPart = new MimeBodyPart();
                mimeBodyPart.setDataHandler(new DataHandler(dataSource));
                mimeBodyPart.setFileName(MimeUtility.encodeText(String.format("%s.pdf", subject)));
                multipart.addBodyPart(mimeBodyPart);
            }
            if(CollectionUtils.isNotEmpty(excelFiles)){
                for(File file : excelFiles) {
                    DataSource dataSource = new FileDataSource(file);
                    MimeBodyPart mimeBodyPart = new MimeBodyPart();
                    mimeBodyPart.setDataHandler(new DataHandler(dataSource));
                    mimeBodyPart.setFileName(file.getName());
                    multipart.addBodyPart(mimeBodyPart);
                }
            }

            EmailUtils.setRecipients(toEmails, mimeMessage,Message.RecipientType.TO);
            EmailUtils.setRecipients(ccEmails, mimeMessage,Message.RecipientType.CC);
            mimeMessage = messageHelper.getMimeMessage();
            mailSender.send(mimeMessage,mimeMessage);
            logger.info("sendBatchMailByTemplate: 发送成功");
        }finally {
            if(null != pdfFile) {
                pdfFile.delete();
            }
            if(CollectionUtils.isNotEmpty(excelFiles)) {
                for (File file : excelFiles) {
                    file.delete();
                }
            }
        }
    }

    /**
     * 查询项目发件人邮箱
     * @return
     */
    public JavaMailSenderImpl getMailSender(Integer projectId, String projectName){
        ProjectInfo projectInfo = projectMapper.selectByProjectId(projectId,projectName);
        logger.info(projectInfo.getMailSender(),"------------------");
        // 不配置的话，就走系统默认的配置
        if(StringUtils.isEmpty(projectInfo.getMailSender())){
            return (JavaMailSenderImpl) this.mailSender;
        }
        JavaMailSenderImpl mailSender = new JavaMailSenderImpl();
        /*Properties properties = new Properties();
        properties.put("mail.smtp.auth", "true");
        //properties.put("mail.smtp.auth.mechanisms", "digest");
        properties.put("mail.smtp.auth.mechanisms", "digest");
        properties.setProperty("mail.debug", "true");
        mailSender.setJavaMailProperties(properties);*/
        mailSender.setHost(projectInfo.getMailServer());
        mailSender.setPort(Integer.parseInt(projectInfo.getMailPort()));
        mailSender.setUsername(projectInfo.getMailSender());
        byte[] decodedBytes = Base64.getDecoder().decode(projectInfo.getMailPassword());
        String decodedString = new String(decodedBytes);
        mailSender.setPassword(decodedString);
        return mailSender;
    }

}
